package yxy.game.pm2.command.union;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlayerMessage;
import yxy.game.pm2.message.UnionMessage;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.player.UnionPlayer;
import yxy.game.pm2.module.union.player.UnionPlayerContribution;

import java.util.Set;

/** 联盟 联盟管理界面 */
@MessageType(proto = Command.UnionManage, classtype = UnionMessage.UnionManageRequest.class)
public class CMD_UnionManage extends Command<UnionMessage.UnionManageRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionMessage.UnionManageRequest request) {
		String playerCode = messageSource.getTag();

		UnionMessage.UnionManageResponse.Builder response = UnionMessage.UnionManageResponse.newBuilder();

		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnion(entry);
		if (!result.equals(Result.UnionIn)) {
			send(messageSource, response, result);
			return;
		}
		UnionBean union = entry.getUnionBean();

		Set<String> members = union.members();
		for (String member : members) {
			try {
				UnionPlayer unionPlayer = UnionPlayer.get(member);
				UnionPlayerContribution contribution = unionPlayer.getContribution();
				PlayerBean playerBean = PlayerBean.get(member);
				PlayerMessage.PlayerSimpleInfo.Builder playerInfo = new PlayerHandle().playerSimpleInfo(playerBean);
				playerInfo.setOnline(playerBean.online());

				UnionMessage.UnionMember.Builder builder = UnionMessage.UnionMember.newBuilder();
				builder.setInfo(playerInfo);
				builder.setContribDaliy(contribution.getContribDaliy());
				builder.setContribution(contribution.getContribution());
				if (union.getLeader().equals(member)) {
					builder.setType(UnionMessage.MemberType.LEADER);
				} else if (union.getViceList().contains(member)) {
					builder.setType(UnionMessage.MemberType.VICE);
				} else {
					builder.setType(UnionMessage.MemberType.MEMBER);
				}
				response.addMembers(builder);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, UnionMessage.UnionManageResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}